package ModelImplementation

import (
	"SalaryPayment/Model"
	"time"
)

type UnionAffiliation struct {
	itsMemberId      int
	itsDues          float64
	itsServiceCharge map[time.Time]ServiceCharge
}

func (ua *UnionAffiliation) GetServiceCharge(date time.Time) ServiceCharge {
	return ua.itsServiceCharge[date]
}

func (ua *UnionAffiliation) AddServiceCharge(date time.Time, amount float64) {
	sc := NewServiceCharge(date, amount)
	ua.itsServiceCharge[date] = sc
}

func (ua *UnionAffiliation) GetDues() float64 {
	return ua.itsDues
}

func (ua *UnionAffiliation) GetMemberId() int {
	return ua.itsMemberId
}

func (ua *UnionAffiliation) CalculateDeductions(SC Model.Salarycheck) float64 {
	totalServiceCharge, totalDues := 0.0, 0.0

	for date, sc := range ua.itsServiceCharge {
		dt1 := SC.GetSalaryStartDate()
		dt2 := SC.GetSalaryEndDate()

		if date.After(dt1) && date.Before(dt2) {
			totalServiceCharge += sc.GetAmount()
		}
	}

	fridays := ua.numberOfFridayInPayPeriod(SC.GetSalaryStartDate(),
		SC.GetSalaryEndDate())
	totalDues = ua.itsDues * float64(fridays)
	return totalDues + totalServiceCharge
}

func (ua *UnionAffiliation) numberOfFridayInPayPeriod(payPeriodStart, payPeriodEnd time.Time) int {
	friday := 0

	for date := payPeriodStart; date.Before(payPeriodEnd); date.AddDate(0, 0, 1) {
		if date.Weekday() == time.Friday {
			friday++
		}
	}
	return friday
}

func NewUnionAffiliation(memberId int, dues float64) Model.Affiliation {
	return &UnionAffiliation{itsMemberId: memberId, itsDues: dues}
}